package com.joolun.cloud.weixin.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.iecg.api.entity.IecgUser;
import com.joolun.cloud.weixin.admin.config.mp.WxMpConfiguration;
import com.joolun.cloud.weixin.admin.service.WxTemplateService;
import com.joolun.cloud.weixin.common.feign.FeignIecgUserInfoService;
import com.pig4cloud.pigx.common.core.constant.CacheConstants;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
@Slf4j
@AllArgsConstructor
public class WxTemplateServiceImpl implements WxTemplateService {

	private final RedisTemplate redisTemplate;

	private final FeignIecgUserInfoService feignIecgUserInfoService;


	public static JSONObject sendPost(String url, JSONObject jsonObj) throws ClientProtocolException, IOException {
		HttpPost httpPost = new HttpPost(url);
		StringEntity entity = new StringEntity(jsonObj.toString(), "utf-8");
		entity.setContentEncoding("UTF-8");
		entity.setContentType("application/json");
		httpPost.setEntity(entity);
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpResponse response=httpClient.execute(httpPost);
		String result = EntityUtils.toString(response.getEntity(), "UTF-8");
		//输出调用结果
		if(response != null && response.getStatusLine().getStatusCode() == 200) {
			// 生成 JSON 对象
			JSONObject obj = JSONObject.parseObject(result);
			return obj;
		}
		return null;

	}

	@Override
	@SneakyThrows
	public void send(Long notice, String toOpenId, String bizId) {

		JSONObject obj = new JSONObject();
		WxMpService wxMpService = WxMpConfiguration.getMpService("wxd9bd8e84c4a9aba0");

		String token = wxMpService.getAccessToken();

			String path = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;

			if(notice == 0){
				obj.put("template_id", "bFfa-KhwMGTgWk5ym03f_FdkaUKogte18wFC0ToNHxI");
			}else {
				obj.put("template_id", "H36x_vOQ_Pe0LDq_VubV3B7k3_ifHnKSdCXB93Gc8ow");
			}

			String redictUrl = "http://wx.zhongkehuashi.com/ecgDetail?bizId="+ bizId;
			obj.put("url", redictUrl);
		    obj.put("touser", toOpenId);

//			JSONObject miniprogram = new JSONObject();
//			miniprogram.put("appid", appid);
//			miniprogram.put("pagepath", "/");
//			obj.put("miniprogram", miniprogram);
			JSONObject data = new JSONObject();

			Map map1 = new HashMap();
			if(notice == 0){
				map1.put("value", "健康报告提醒");
			}else {

				map1.put("value", "报告生成通知");
			}
			data.put("first", map1);
			Map map2 = new HashMap();
			if(notice == 0){

				map2.put("value","报告主题");
			}else {
				map2.put("value", LocalDateTime.now().toString());
			}
			data.put("keyword1", map2);
			//map2.put("color","#173177");

			Map map3 = new HashMap();

			if(notice ==0){

				map3.put("value", "血压");
			}else {
               map3.put("value", "风险等级");
			}
			data.put("keyword2", map3);
			//map3.put("color","#173177");

			Map map4= new HashMap();
			if(notice ==0){
				map4.put("value", "心率");

			}else {
				map4.put("value", LocalDateTime.now().toString());

			}
			data.put("keyword3", map4);

			if(notice ==0){
				Map map6 = new HashMap();
				map6.put("value", "小结");
				data.put("keyword4", map6);
			}

			Map map5= new HashMap();
			map5.put("value","备注");
			data.put("remark", map5);

			obj.put("data", data);
			log.info("send Param = {}", obj);
			sendPost(path, obj);
			if(notice ==0){
				R<IecgUser> r = feignIecgUserInfoService.infoByOpenId(toOpenId, SecurityConstants.FROM);
				IecgUser iecgUser = r.getData();
				BoundSetOperations boundSetOperations = redisTemplate.opsForSet().getOperations().boundSetOps(CacheConstants.BIND_ME + "_"+ iecgUser.getId());
				Set<String> members = boundSetOperations.members();
				members.stream().forEach(member -> {
					obj.put("touser", member);
					try {
						sendPost(path, obj);

					}catch (Exception e){

					}
				});

			}
	}

}
